package cn.steel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.domain.entity.Product;
import cn.steel.domain.entity.User;
import cn.steel.domain.vo.ProductVo;
import cn.steel.mapper.ProductMapper;
import cn.steel.mapper.UserMapper;
import cn.steel.service.BrowseHistoryService;
import com.github.pagehelper.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class BrowseHistoryServiceImpl implements BrowseHistoryService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ProductMapper productMapper;
    private final UserMapper userMapper;
    private static final String BROWSE_HISTORY_KEY = "browse:history:user:%d";
    private static final long EXPIRE_DAYS = 30;

    @Override
    public void addBrowseHistory(Long userId, Long productId) {
        validateBuyer(userId);
        String key = String.format(BROWSE_HISTORY_KEY, userId);
        redisTemplate.opsForList().leftPush(key, productId);
        redisTemplate.expire(key, EXPIRE_DAYS, TimeUnit.DAYS);
        log.info("Added browse history: userId={}, productId={}", userId, productId);
    }

    @Override
    public Page<ProductVo> getBrowseHistoryPaginated(Long userId, int page, int size) {
        validateBuyer(userId);
        String key = String.format(BROWSE_HISTORY_KEY, userId);
        Long total = redisTemplate.opsForList().size(key);
        if (total == null || total == 0) {
            return new Page<>();
        }

        int start = (page - 1) * size;
        int end = start + size - 1;
        List<Object> productIds = redisTemplate.opsForList().range(key, start, end);
        if (productIds == null || productIds.isEmpty()) {
            return new Page<>();
        }

        List<ProductVo> productVos = new ArrayList<>();
        for (Object pid : productIds) {
            Long productId = Long.valueOf(pid.toString());
            Product product = productMapper.findProductById(productId);
            if (product != null) {
                ProductVo vo = new ProductVo();
                BeanUtil.copyProperties(product, vo);
                productVos.add(vo);
            }
        }

        Page<ProductVo> pageResult = new Page<>(page, size);
        pageResult.setTotal(total);
        pageResult.addAll(productVos);
        return pageResult;
    }

    @Override
    public void clearBrowseHistory(Long userId) {
        validateBuyer(userId);
        String key = String.format(BROWSE_HISTORY_KEY, userId);
        redisTemplate.delete(key);
        log.info("Cleared browse history for user: {}", userId);
    }

    /**
     * 验证用户是否为 BUYER 角色
     *
     * @param userId 用户 ID
     */
    private void validateBuyer(Long userId) {
        User user = userMapper.findUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (!"BUYER".equals(user.getRole())) {
            throw new IllegalArgumentException("仅买家用户可以操作浏览历史");
        }
    }
}